import React, { useState } from 'react'
import { Image, Text, View } from 'remax/one'
import { requestPayment, hideLoading } from 'remax/wechat'
import RecycleView from 'remax-recycle-view/lib'
import { Button, Icon, Popup, Row, Space, Tag } from 'annar'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import useCloud, { mutateCloud, requestCloud } from '@/hooks/use-cloud'
import useUser from '@/hooks/use-user'
import Login from '@/components/login'
import styles from './index.css'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

interface Checkinable {
  setCheckin: (_id: string) => void
}

const OrderItem = ({
  _id,
  promotionCast: { promotion },
  payment,
  cost,
  status,
  createAt,
  setCheckin,
}: WBG.Order & Checkinable) => {
  const refresh = async () => {
    try {
      await requestCloud('pay', { $url: 'update-order', _id })
      mutateCloud('list-order')
      mutateCloud('get-user')
    } catch (e) {}
  }

  return (
    <View className={styles.itemArea}>
      <View
        className={styles.itemBox}
        hoverClassName="hover"
        onTap={async () => {
          switch (status) {
            case 0:
              await requestPayment(payment)
              refresh()
              break
            case 1:
              setCheckin(_id)
              break
          }
        }}
      >
        <Row className={styles.fullHeight} align="middle">
          <View className={styles.itemBoxLeft}>
            <Image
              className={styles.avatarImg}
              src={promotion.imgUrls[0]}
              mode="aspectFill"
            />
          </View>
          <Space className={styles.itemBoxRight} direction="vertical" size={12}>
            <Row justify="space-between" align="middle">
              <View className="large-text ellipsis">{promotion.name}</View>
              {status === 0 ? (
                <Row>
                  <Button
                    size="small"
                    onTap={e => {
                      e.stopPropagation()
                      refresh()
                    }}
                  >
                    <Icon type="refresh" />
                  </Button>
                  <Tag className="no-border" color="red">
                    未支付
                  </Tag>
                </Row>
              ) : status === 1 ? (
                <Tag className="no-border" color="yellow">
                  未签到
                </Tag>
              ) : (
                <Tag className="no-border" color="green">
                  已完成
                </Tag>
              )}
            </Row>
            <View className="small-text ellipsis">{promotion.description}</View>
            <Row justify="space-between" align="bottom">
              <Space align="center" size={12}>
                <Text className="large-text alarm-text">￥{cost}</Text>
                <Text className="deleted-text">
                  ￥{promotion.originalPrice}
                </Text>
                <Tag className="no-border" color="red">
                  {Math.round((cost / promotion.originalPrice) * 100) / 10} 折
                </Tag>
              </Space>
              <Text className="small-text">{dayjs(createAt).fromNow()}</Text>
            </Row>
          </Space>
        </Row>
      </View>
    </View>
  )
}

export default () => {
  const { data: uData } = useUser()
  const { data, mutate } = useCloud('list-order')
  const [loading, setLoading] = useState(false)
  const [checkin, setCheckin] = useState<string>()

  return (
    <Login>
      <View className={styles.basicArea}>
        <Row align="middle">
          <View className={styles.basicAreaLeft}>
            <Image
              className={styles.profileImg}
              src={uData?.avatarUrl}
              mode="aspectFill"
            />
          </View>
          <View className="xlarge-text ellipsis">{uData?.nickName}</View>
        </Row>
        <Row className={styles.centerText} justify="space-around">
          <View>
            <View>
              <Text className="large-text bold">
                {uData?.stats?.orderCount || 0}
              </Text>
              <Text>次</Text>
            </View>
            <Text>购买次数</Text>
          </View>
          <View>
            <View>
              <Text className="large-text bold">￥</Text>
              <Text>{uData?.stats?.costSaving || 0}</Text>
            </View>
            <Text>共节省</Text>
          </View>
        </Row>
      </View>
      {data &&
        (data.length ? (
          <RecycleView
            className={styles.mainArea}
            refresherEnabled
            refresherTriggered={loading}
            onRefresherRefresh={async () => {
              setLoading(true)
              await mutate()
              setLoading(false)
            }}
            data={data.map((v: WBG.Order) => ({ ...v, height: 220 }))}
            renderItem={(item, index) => {
              return (
                <OrderItem
                  {...((item as unknown) as WBG.Order)}
                  setCheckin={setCheckin}
                />
              )
            }}
          />
        ) : (
          <View className="empty-view small-text">您没有订单</View>
        ))}
      <Popup
        open={!!checkin}
        closeable={true}
        title="请让商家扫描二维码完成签到"
        style={{ textAlign: 'center', width: '80%', padding: 30 }}
        onClose={() => {
          setCheckin(undefined)
        }}
      >
        <Image
          className={styles.qrcodeImg}
          src={`https://www.zhihu.com/qrcode?url=https://wbg.shihangdushu.com/business/ticket/${checkin}`}
          mode="aspectFit"
        />
      </Popup>
    </Login>
  )
}
